<?php
namespace control;
/*
*计时工资类
*/

class pieceHourClass extends adIndexClass
{
    private const page = 'pieceHour';
    private const title = '计时工资';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => "日期",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'team'  => [
                        'name'  => '班组',
                        'width' => 250,
                    ],
                    'staffId'         => [
                        'name'  => '员工',
                        'width' => 250,
                    ],
                    'hour'          => [
                        'name'  => '工时',
                        'width' => 250,
                    ],
                    'price'          => [
                        'name'  => '工时单价',
                        'width' => 250,
                    ],
                    'salary'          => [
                        'name'  => '计时工资',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "班组"   => selectMultiple(array("name" => "teamId", "title" => "班组",'where'=>"coid = '".self::$coid."'",  "table" => "team",  'sqlField' => 'name', 'class' => 'width200')),
                    '员工'  => selectMultiple(array("name" => "stid", "table" => "staff",  'sqlField' => 'name', 'sqlId' => 'stid', 'class' => 'width200')),
                    "日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
        );
        //全等查询数组
        $equal = array(
            "staffId"=>$this->post('stid'),
            "teamId"=>$this->post('teamId'),
        );
        $where = "";
        if ($this->post('createTime')) {
            $where.=self::timeComparison($this->post('createTime'),field: 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where .= search(array("like" => $like, "=" => $equal));
        $totalWhere = $where;
        $where .= " and coid = '".self::$coid."' ";
        $page = $this->page(array(
            "table" => "timing_report",
            'field'=>"distinct recordDate,teamId,staffId",
            "where" => $where,
            'order'=>$orderBy['orderBy']
        ));
        static::rSet(self::$stid.self::page.'Sql', $page['fullSql']);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $hour = find(array('table'=>'timing_report','where'=>"recordDate = '$array[recordDate]' and teamId = '$array[teamId]' and staffId = '$array[staffId]' and coid = '".self::$coid."'",'sum'=>"hour"));
            $teamMx = query('team_detail',"orderId = '$array[teamId]' and stid = '$array[staffId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'team':
                        $team = query('team',"id = '$array[teamId]'");
                        $row[] = $team['name'];
                        break;
                    case 'staffId':
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    case 'hour':
                        $row[] = $hour;
                        break;
                    case 'price':
                        $row[] = $teamMx['price'];
                        break;
                    case 'salary':
                        $row[] = self::formattingFigure($hour*$teamMx['price']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => 'timing_report as tr join team_detail as td on td.orderId = tr.teamId and td.stid = tr.staffId ',
            'single' => $totalWhere." and tr.coid = '".self::$coid."' ",
            'field'  => "ifnull(sum(tr.hour),0) as hour,ifnull(sum(tr.hour*td.price),0) as salary",
        ]);
        $total    = [
            'hour'        => self::lostZero($totalQuery['hour'], 'numPrecision'),
            'salary'        => self::formattingFigure($totalQuery['salary']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            $sql = static::rGet(self::$stid.self::page.'Sql');
            $result   = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $team = query('team',"id = '$array[teamId]'");
                $hour = find(array('table'=>'timing_report','where'=>"recordDate = '$array[recordDate]' and teamId = '$array[teamId]' and staffId = '$array[staffId]' and coid = '".self::$coid."'",'sum'=>"hour"));
                $teamMx = query('team_detail',"orderId = '$array[teamId]' and stid = '$array[staffId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '日期'=>$array['recordDate'],
                            '班组'=> $team['name'],
                            '员工'=> self::findStaff($array['staffId']),
                            '工时'=>$hour,
                            '工时单价'=>$teamMx['price'],
                            '计时工资'=>self::formattingFigure($hour*$teamMx['price']),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了计时工资表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "计时工资表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'班组',
                    'aliasName'=>'班组',
                ],
                [
                    'columnName'=>'员工',
                    'aliasName'=>'员工',
                ],
                [
                    'columnName'=>'工时',
                    'aliasName'=>'工时',
                ],
                [
                    'columnName'=>'工时单价',
                    'aliasName'=>'工时单价',
                ],
                [
                    'columnName'=>'计时工资',
                    'aliasName'=>'计时工资',
                ],
            ]
        };
    }
}

